package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.auth.domain.DataNode;
import com.example.auth.domain.vo.DataNodeVo;
import com.example.auth.service.DataNodeService;
import com.example.config.ResultUtil;
import com.example.config.exception.GlobalExcetion;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/node")
public class DataNodeController {

    @Autowired
    private DataNodeService service;

    @GetMapping("/getone")
    public DataNode getOneController(@RequestParam("id")String id){
        DataNode dataNode =service.getById(id);
        return dataNode;
    }

    @GetMapping("/getone/servername")
    public DataNode getOneServerNameController(@RequestParam("serverName")String serverName){
        DataNode dataNode =service.getByNodeServerName(serverName);
        return dataNode;
    }

    @GetMapping("/getallnode")
    public List<DataNode> getAllNodeController(){
        List<DataNode> dataNodeList =service.list();
        return dataNodeList;
    }

    @GetMapping("/page")
    public JSONObject page(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                           @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize,
                           @RequestParam("nodeName")String nodeName) {
        IPage<DataNode> page=service.page(pageNum,pageSize,nodeName);
        return ResultUtil.successInfo(page);
    }

    @PostMapping("/saveorupdate")
    public JSONObject saveorupdate(@RequestBody @Validated DataNodeVo vo) throws GlobalExcetion {
        DataNode config = new DataNode();
        BeanUtils.copyProperties(vo, config);
        config.setIsDeleted(0);
        if(vo.getId()==null){
            service.saveDataNode(config);
        }else {
            DataNode dataNode=service.getById(vo.getId());
            if(dataNode==null){
                throw new GlobalExcetion(1,"更新节点不存在");
            }
            if(!dataNode.getNodeServerName().equals(vo.getNodeServerName())){
                DataNode node=service.getByNodeServerName(vo.getNodeServerName());
                if(node!=null){
                    throw new GlobalExcetion(1,"存在相同服务名");
                }
            }
            BeanUtils.copyProperties(vo,dataNode);
            service.updateDataNode(dataNode);
        }
        return ResultUtil.successInfo("操作成功");
    }



}
